<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="1200px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建MQTT" : "编辑MQTT" }}</span>
        <span class="el-icon-close g9 f26 poi" @click="close"></span>
      </div>
    </div>

    <div class="pl30 pr30">
      <el-row :gutter="40" type="flex">
        <el-col :span="10">
          <el-form
            label-position="top"
            :model="formData"
            ref="form"
            label-width="120px"
          >
            <el-form-item
              label="MQTT KEY"
              prop="key"
              :rules="[
                {
                  required: true,
                  message: 'MQTT KEY不能为空',
                  trigger: 'change',
                },
                {
                  pattern: COMMON_CODE_28I_REG.pattern,
                  message: '请输入有效的MQTT KEY',
                  trigger: 'change',
                },
              ]"
            >
              <template slot="label"
                >MQTT KEY
                <el-tooltip
                  popper-class="custom-popper"
                  :content="COMMON_CODE_28I_REG.message"
                  placement="top"
                >
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-input
                :disabled="!isNew"
                v-model="formData.key"
                placeholder="请输入MQTT KEY"
                :maxlength="28"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item
              label="MQTT名称"
              prop="name"
              :rules="[
                {
                  required: true,
                  message: 'MQTT名称不能为空',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                :disabled="!isNew"
                v-model="formData.name"
                placeholder="请输入MQTT名称"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>

            <el-form-item label="描述">
              <el-input
                type="textarea"
                v-model="formData.notes"
                placeholder="请输入描述"
                :maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="14" style="border-left: 1px solid #dcdfe6">
          <el-tabs v-model="activeTab">
            <el-tab-pane
              v-for="(item, index) in envConfigList"
              :key="index"
              :label="item.name"
              :name="item.key"
            >
              <MqttEnvForm :ref="`${item.key}_EnvForm`" :env="item.key" />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <div slot="footer" class="tr">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { COMMON_ENV_ENUM } from "@/utils/enum"
import { COMMON_CODE_28I_REG } from "@/utils/reg"

import MqttEnvForm from "./MqttEnvForm"
import { postHmmqtt, putHmmqtt } from "@/apis/paas/HmMqttLinkController.js"
import { getHmenvironmentList } from "@/apis/paas/HmEnvironmentController.js"
const defaultTab = Object.keys(COMMON_ENV_ENUM)[0]

export default {
  name: "HttpServiceForm",
  components: {
    MqttEnvForm,
  },
  data() {
    return {
      COMMON_ENV_ENUM,
      COMMON_CODE_28I_REG,
      showVisible: false,
      envConfigList: [], // 系统显示的环境
      envConfigHiddenList: [], // 隐藏的配置项
      formData: {},
      activeTab: defaultTab,
      callback: () => {},
    }
  },

  computed: {
    isNew() {
      return !this.formData.id
    },
  },

  methods: {
    async open(data = {}, callback) {
      this.envConfigList = await getHmenvironmentList({ hidden: 0 })
      this.showVisible = true
      this.callback = callback
      const mqttSettings = data.mqttSettings || []
      this.formData = {
        ...data,
      }

      this.activeTab = defaultTab

      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        // 获取隐藏了的配置
        mqttSettings.forEach((item) => {
          const res = this.envConfigList.find(
            (config) => config.key === item.env
          )
          if (!res) {
            this.envConfigHiddenList.push(item)
          }
        })
        this.envConfigList.forEach((item, index) => {
          // 获取对应环境的配置项
          const config = (mqttSettings || []).find(
            (config) => config.env === item.key
          )
          // 对应ref的form
          const form = this.$refs[item.key + "_EnvForm"][0]
          form.setData(config)
        })
      })
    },

    close() {
      this.showVisible = false
      this.envConfigHiddenList = []
    },

    async submit() {
      try {
        await this.$refs.form.validate()
        const { id, key, name, notes } = this.formData
        const envResList = await Promise.all(
          this.envConfigList.map((item, index) => {
            const form = this.$refs[item.key + "_EnvForm"][0]
            return form.getData()
          })
        )
        const mqttSettings = []
        for (var i = 0; i < envResList.length; i++) {
          const res = envResList[i]
          if (res === false) {
            this.activeTab = this.envConfigList[i].key
            return
          }
          res.mqttKey = key
          res.host && mqttSettings.push(res)
        }

        let params = {}
        let request = null
        if (this.isNew) {
          request = postHmmqtt
          params = { key, name, notes }
        } else {
          request = putHmmqtt
          params = { id, name, notes }
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key]
        }
        params.mqttSettings = [...mqttSettings, ...this.envConfigHiddenList]
        request(params).then((res) => {
          this.close()
          this.callback()
        })
      } catch (error) {
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>
